package com.zzh.myapplication.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import net.icarplus.car.R;
import net.icarplus.car.adapter.SortAdapter;
import net.icarplus.car.bean.City;
import net.icarplus.car.bean.CityInfo;
import net.icarplus.car.bean.SortBean;
import net.icarplus.car.constant.UrlValues;
import net.icarplus.car.manager.AppManager;
import net.icarplus.car.manager.BaseActivity;
import net.icarplus.car.tools.CharacterParser;
import net.icarplus.car.tools.JsonUtil;
import net.icarplus.car.tools.LoadingUtil;
import net.icarplus.car.tools.PinyinComparator;
import net.icarplus.car.tools.ToolBarHelper;
import net.icarplus.car.views.ClearEditText;
import net.icarplus.car.views.SideBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import okhttp3.Call;

/**
 * 项目名称：icarplus-car-android
 * 类描述：
 * 创建人：Gophy
 * 创建时间：16/3/12 10:56
 * 修改人：Gophy
 * 修改时间：16/3/12 10:56
 * 修改备注：
 */
public class SelectCityActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private Toolbar toolbar;

    private List<CityInfo> querycitylist;
    View view = null;
    private ListView sortListView;
    private SideBar sideBar;
    private TextView dialog;
    private SortAdapter adapter;
    private ClearEditText mClearEditText;

    private JSONArray array;
    private JSONObject jsons;

    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<SortBean> SourceDateList;

    private LoadingUtil loadingUtil;

    public static int REQUESTCITY = 2000;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0://查询到充电桩的详细信息后
                    break;
                case 1:
                    String message = (String) msg.obj;
                    showAlerDialog("提示", message, null);
                    break;
                default:
                    break;
            }
        }

    };

    private void toResult(JSONArray cityData) {
        if (cityData.length() > 0) {
            SourceDateList.clear();
        }
        for (int i = 0; i < querycitylist.size(); i++) {
            SortBean sortModel = new SortBean();
            sortModel.setName(querycitylist.get(i).getOrgShortname());
            sortModel.setCityCode(querycitylist.get(i).getOrgCode());
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(querycitylist.get(i).getOrgShortname());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }
            SourceDateList.add(sortModel);
        }
//		SourceDateList = filledData(getResources().getStringArray(R.array.date));

//		// 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
//		adapter = new SortAdapter(this, SourceDateList);
//		sortListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void setContent() {
        // 设置输入框的弹出效果
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
                        | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_select_city);
    }

    @Override
    public void initComponent() {
        City city = new City();
        city.setCityName("");

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ToolBarHelper.setNormalTitleAndBack(this, toolbar, getString(R.string.select_city));
        characterParser = CharacterParser.getInstance();

        pinyinComparator = new PinyinComparator();

        sideBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.dialog);
        sideBar.setTextView(dialog);

        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }

            }
        });

        sortListView = (ListView) findViewById(R.id.country_lvcountry);
        sortListView.setOnItemClickListener(this);
        SourceDateList = new ArrayList<SortBean>();

        adapter = new SortAdapter(this, SourceDateList);

        loadingUtil = new LoadingUtil(this, "查询中...");
        this.loadingUtil.startShowLoading();

        JSONObject json = new JSONObject();
        try {
            json.put("cityName", "");


        } catch (JSONException e) {
            e.printStackTrace();
        }

        OkHttpUtils.get().url(UrlValues.SEARCH_CITY).addParams("input", json.toString()).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e) {
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject result = new JSONObject(response.toString());
                    if (JsonUtil.isValid(response)) {
                        array = result.getJSONArray("queryCityList");
                        for (int i = 0; i < array.length(); i++) {
                            jsons = array.getJSONObject(i);
                            SortBean sort = new SortBean();
                            sort.setName(jsons.getString("areaName"));
                            sort.setCityCode(jsons.getString("areaCode"));

                            //汉字转换成拼音
                            String pinyin = characterParser.getSelling(jsons.getString("areaName"));
                            String sortString = pinyin.substring(0, 1).toUpperCase();
                            // 正则表达式，判断首字母是否是英文字母
                            if (sortString.matches("[A-Z]")) {
                                sort.setSortLetters(sortString.toUpperCase());
                            } else {
                                sort.setSortLetters("#");
                            }
                            SourceDateList.add(sort);
                        }
                        Collections.sort(SourceDateList, pinyinComparator);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                adapter.notifyDataSetChanged();
                if (SourceDateList != null) {
                    sortListView.setAdapter(adapter);
                    SelectCityActivity.this.loadingUtil.stopShowLoading();
                }

            }
        });

//        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view,
//                                    int position, long id) {
//                //这里要利用adapter.getItem(position)来获取当前position所对应的对象
////				Toast.makeText(getApplication(), ((SortModel)adapter.getItem(position)).getName(), Toast.LENGTH_SHORT).show();
//                String whatActivity = getIntent().getStringExtra("Activity");
//                Intent intent = null;
//                if (whatActivity != null && whatActivity.equals("RentCar")) {
//                    intent = new Intent(SelectCityActivity.this, RentCarActivity.class);
//                    String cityFormer = getIntent().getStringExtra("city");
//                    Log.e("Long", "cityFormer:" + cityFormer);
//                    String countyformer = getIntent().getStringExtra("county");
//                    String cityNow = ((SortBean) adapter.getItem(position)).getName();
//                    Log.e("Long", "countyformer:" + countyformer);
//                    Log.e("Long", "cityNow:" + cityNow);
//                    if (cityFormer == null) {
//                        intent.putExtra("change", true);
//                    } else {
//                        if (cityFormer.contains("" + cityNow)) {
//                            intent.putExtra("change", false);
//                        } else {
//                            intent.putExtra("change", true);
//                        }
//                    }
//                } else {
//                    intent = new Intent(SelectCityActivity.this, DotListActivity.class);
//                }
//                intent.putExtra("city", "" + ((SortBean) adapter.getItem(position)).getName());
//                intent.putExtra("cityCode", "" + ((SortBean) adapter.getItem(position)).getCityCode());
//                setResult(3, intent);
//                finish();
//            }
//        });

//		SourceDateList = filledData(getResources().getStringArray(R.array.date));


        mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);

        //根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    public void setListener() {

    }

    @Override
    public void onAfterInit() {

    }

    @Override
    public void onClick(View view) {

    }

    private void filterData(String filterStr) {
        List<SortBean> filterDateList = new ArrayList<SortBean>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            for (SortBean sortModel : SourceDateList) {
                String name = sortModel.getName();
                if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Bundle bundle = new Bundle();
        bundle.putString("cityName", ((SortBean) adapter.getItem(position)).getName());
        bundle.putString("cityCode", ((SortBean) adapter.getItem(position)).getCityCode());
        Intent data = new Intent();
        data.putExtra("bundle", bundle);
        setResult(REQUESTCITY, data);
        AppManager.getAppManager().finishActivity();
    }


}
